import json

from flask_restful import Resource,reqparse
from flask import current_app,request
from common.kit_工具包.demo_sms_send import send_sms
from common.kit_工具包.limiter_限流器 import limiter as lmt
import random

from common.kit_工具包.shopping_redis import redis_client
from shopping_items.resources.user_模块 import  constants
#from common.kit_工具包.shopping_redis import redis_client
from flask_restful.reqparse import RequestParser
from common.kit_工具包 import parser
from common.models.user import User
from common.models import db
from common.kit_工具包.token_itsdangerous import generate_tokens
from  common.kit_工具包.decorators import login_required

class ur_resource(Resource):

    method_decorators = {

        'get':[login_required],
        'post':[login_required]
    }

    def get(self):
        current_app.logger.info('这是我的第一个测试日志 ')
        return {"你好":'123'}


class User_SMS(Resource):
    Error_message='请稍后再试'

#     decorators = [
#
# lmt.limit(constants.LIMIT_SMS_CODE_BY_MOBILE,
#           key_func=lambda:request.args.get('phone'),
#           error_message=Error_message),
# lmt.limit(constants.LIMIT_SMS_CODE_BY_IP,
#           key_func=lambda: request.args.get('phone'),
#           error_message=Error_message)
#
#     ]

    def get(self):
        phone=request.args.get('phone')

        code=random.randint(1000,9999)
        result1=send_sms(phone,str(code))
        result=json.loads(result1)
        result['phone']=phone
        # print(phone,constants.SMS_CODE_EXPIRES,code)

        redis_client.setex('shopping:code:{}'.format(phone),constants.SMS_CODE_EXPIRES,code)

        print(result,'测试')

        return result

class verify_SMS(Resource):
    def post(self):
        rp=RequestParser()
        rp.add_argument('phone',type=parser.mobile,required=True)
        rp.add_argument('code',type=parser.regex(r'^\d{4}$'),required=True)
        args=rp.parse_args()
        phone=args.phone
        code=args.code
        #从数据库中得到之前保存的验证码

        key='shopping:code:{}'.format(phone)
        try:
            real_code=redis_client.get(key)
        except ConnectionError as e:
            current_app.logger.error(e)
            return {'message':'redis db connent error'},400

       #if not real_code or real_code.decode()!=code:
            return {'message':'Invalid code'},400

        return {'phone':phone,'msg':'code success'}

class Register_resourse(Resource):
    def post(self):
        rp = RequestParser()
        rp.add_argument('phone', required=True)
        rp.add_argument('username', required=True)
        rp.add_argument('password',required=True)
        rp.add_argument('email',type=parser.email)
        arg=rp.parse_args()
        phone=arg.phone
        username=arg.username
        password=arg.password
        email=arg.email

        #验证用户名是否唯一

        u= User.query.filter(User.username==username).first()
        if u:
            current_app.logger.info('{}:用户名已经存在，请换一个'.format(username))
            return {'msg:The username already exists',400}

        #把用户数据保存在数据库中
        abc=User(username=username,pwd=password,email=email,phone=phone,status=0)
        db.session.add(abc)
        db.session.commit()
        return {'msg':'OK'}

class Login_resourse(Resource):
    def post(self):
        username=request.form.get('username')
        password=request.form.get('password')

        if not all([username,password]):
            return {'message':'数据不完整'},402

        user= User.query.filter(User.username==username).first()

        if user:
            if user.password=='456':
                token=generate_tokens(user.id)
                return {'message': '登陆成功', 'token': token}

            else:
                return {'meg':'密码错误'}



        return {'message':'用户名或密码错误'},400
class PhoneExist(Resource):
    def post(self):
        phone=request.form.get('phone')
        user=User.query.filter(User.phone==phone).first()
        if user:
            return {'isExist':True,'message':'此手机号已经注册','code':250}
        return {'msg':'手机号不存在'}

class Text(Resource):
    def get(self):
        return {'meg':'欢迎来到德莱联盟'}

class Textpost(Resource):
    def post(self):
        rp=RequestParser()
        rp.add_argument('username',required=True)
        rp.add_argument('pwd', required=True)
        rp.add_argument('repwd', required=True)
        rp.add_argument('phone', required=True)
        rp.add_argument('email', required=True)
        arg=rp.parse_args()
        user=arg.username
        pwd=arg.pwd
        repwd=arg.repwd
        phone=arg.phone
        e_mail=arg.email
        u=User.query.filter(User.username==user).first()
        if u:
            return {'msg':'the username already exists'},400


        else:
             #if pwd!=repwd:
                #return{'msg': 'The two password are different'},400

             abc=User(username=user,password=pwd,repassword=repwd,phone=phone,email=e_mail)

             db.session.add(abc)
             db.session.commit()
             return {'msg':'OK'},200


class login(Resource):
    def post(self):
        username=request.form.get('username')
        password=request.form.get('password')
        if not all([username,password]):
          return {'msg':'数据不完整'}

        user=User.query.filter(User.username==username).first()

        if user:
            #检验密码是否正确
              if user.check_password(password):
                  token=generate_tokens(user.id)
                  return {'msg':'登陆成功','token':token}

        return {'msg':'用户名或者密码错误'}



# 重新登陆获取一下token




